/**
 * Copyright (c) 2022 Beijing Jiaotong University
 * PhotLab is licensed under [Open Source License].
 * You can use this software according to the terms and conditions of the [Open Source License].
 * You may obtain a copy of [Open Source License] at: [https://open.source.license/]
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *
 * See the [Open Source License] for more details.
 *
 * Author: Zhenjie Wei
 * Created: Mar. 13, 2023
 * Supported by: National Key Research and Development Program of China
 */

/**
 * A disposable is a reference to one or more resources that should be released
 * when no longer needed.
 */
export interface IDisposable {
    dispose(): void
}

/**
 * A Disposable store is a collection of disposable resources that are disposed
 * together.
 */
export class Disposable implements IDisposable {

    private _toDispose: IDisposable[] = [];

    /**
     * register a disposable resource with this object.
     */
    protected _register<T extends IDisposable>(t: T): T {
        this._toDispose.push(t);
        return t;
    }

    /**
     * Dispose all registered resources.
     * Once called the object is inoperative.
     */
    public dispose(): void {
        while (this._toDispose.length) {
            const item = this._toDispose.pop();
            if (item) {
                item.dispose();
            }
        }
    }
}